package com.useeinfo.oa.modules.security.extend;

import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.tools.CommonSugar;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.common.config.ConstantKeySession;
import com.useeinfo.oa.modules.base.biz.EnterpriseBiz;
import com.useeinfo.oa.modules.base.entity.Enterprise;
import com.useeinfo.oa.modules.logger.annotations.LoginLogs;
import com.useeinfo.oa.modules.logger.biz.LoginLogBiz;
import com.useeinfo.oa.modules.logger.entity.LoginLog;
import com.useeinfo.oa.modules.security.biz.SystemUserBiz;
import com.useeinfo.oa.modules.security.entity.SystemUser;
import com.useeinfo.oa.modules.security.util.SessionKeyUtils;
import com.xiaoleilu.hutool.util.CollectionUtil;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;


/**
 * 带验证码校验功能的用户名、密码认证过滤器
 * <p/>
 * 支持不输入验证码；支持验证码忽略大小写。
 *
 * @author Long
 */
public class ValidateCodeUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    @Autowired
    private LoginLogBiz loginLogBiz;
    @Autowired
    private SystemUserBiz systemUserBiz;
    @Autowired
    private EnterpriseBiz enterpriseBiz;

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {

        String username = CommonSugar.getTypedDefault(obtainUsername(request), "");
        SystemUser systemUser = systemUserBiz.getByUserAccount(username);
//        SessionKeyUtils.setSessionUser(request, systemUser);
//
//        if (systemUser != null) {
//            if (!"admin".equals(systemUser.getUserAccount())) {
//                QueryParam queryParam = new QueryParam();
//                queryParam.getSqlMap().put("systemUserId", StringConverters.null2String(systemUser.getId()));
//                List<Enterprise> enterprise = enterpriseBiz.findList(queryParam);
//                if (CollectionUtils.isNotEmpty(enterprise)) {
//                    enterprise.sort((o1, o2) -> o1.getId() < o2.getId() ? -1 : 1);
//                    SessionKeyUtils.setSessionEnterprise(request, enterprise.get(0));
//                }
//            }
//        }

        LoginLog loginLog = new LoginLog();
        loginLog.setIp(request.getRemoteAddr());
        loginLog.setType("sign in");
        loginLog.setCreateDate(new Date());
        loginLog.setName(username);
        loginLogBiz.save(loginLog);

        return super.attemptAuthentication(request, response);
    }
}